package sketch.specs;

import java.util.Map;

import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.internal.core.dom.NaiveASTFlattener;

import sketch.ast.ASTUtils;
import sketch.util.Checker;

public class SimpleNameReplaceVisitor extends NaiveASTFlattener {
	
	public final Map<SimpleName, Expression> replace_map;
	
	public SimpleNameReplaceVisitor(Map<SimpleName, Expression> map) {
		Checker.checkNull(map, "The map input could not be null!");
		//System.out.println("replacement map: " + map);
		this.replace_map = map;
	}
	
	@Override
	public boolean visit(SimpleName name) {
		//System.out.println("visit simplename: " + name + "   " + System.identityHashCode(name));
		if(UsedVariableVisitor.isFalsePositive(name)) {
		    return super.visit(name);	
		}
		for(SimpleName replace_name : replace_map.keySet()) {
			if(name.toString().equals(replace_name.toString())) {
				//Checker.checkTrue(replace_name.getStartPosition() != name.getStartPosition(), "Error state");
				Checker.checkTrue(replace_name.getAST() == name.getAST(), "ASTs are different!");
				if(replace_name.getStartPosition() != name.getStartPosition()) {
					//System.out.println(replace_map);
				    ASTUtils.resetSimpleNameIdentifier(name, replace_map.get(replace_name));
				}
				break;
			}
		}
		
		return false; //super.visit(name);
	}
	
}
